#!/usr/bin/env python

import csv
from xml.dom.minidom import parse
from xml.sax.saxutils import unescape

FL_OZ_IN_ML = 29.5735296

def main(filename, outfile):
    out = open(outfile, 'wb')
    out = csv.writer(out)

    dom = parse(filename)
    for entry in dom.getElementsByTagName('entry'):
        name = entry.getElementsByTagName('drink')[0].firstChild.nodeValue
        oz = entry.getElementsByTagName('oz')[0].firstChild.nodeValue
        mg = entry.getElementsByTagName('mg')[0].firstChild.nodeValue
        name, oz, mg = unescape(name), float(oz), float(mg)
        # No caffeine? No point.
        if mg < 0.1:
            continue
        ml = oz * FL_OZ_IN_ML
        if ml < 0.1:
            mg_per_100ml = None
        else:
            mg_per_100ml = mg / ml * 100

        ml, mg, mg_per_100ml = (int(round(ml)), int(round(mg)),
                                int(round(mg_per_100ml)))

        data = (name.encode('utf-8'), str(ml), str(mg), str(mg_per_100ml))
        out.writerow(data)

if __name__ == '__main__':
    import sys
    main(sys.argv[1], sys.argv[2])
